const fs = require('fs')
const path = require('path')
const ejs = require('ejs')

const style = require('./style')
const utils = require('../utils')

// 遍历目录，防止因为目录导致的中断
const read = function(p, fn) {
  const pa = fs.readdirSync(p)
  pa.forEach((item) => {
    let np = path.join(p, item)
    let info = fs.statSync(np)
    if (info.isDirectory()) {
      read(np, fn)
    } else {
      fn(p, item)
    }
  })
}

const fn = (tmp, dest, data, dir) => {
  read(path.join(tmp, dir), (p, f) => {
    const names = p.split('/')
    const name = names[names.length - 1]

    if (/.css$/.test(f)) {
      style(tmp, dest, data, path.join(dir, name), 'index')
    } else {
      ejs.renderFile(path.join(tmp, dir, name, f), data, (err, res) => {
        if (err) throw err
        if (!fs.existsSync(path.join(dest, dir, name))) {
          utils.mkdirsSync(path.join(dest, dir, name))
        }
        fs.writeFileSync(path.join(dest, dir, name, f), res)
      })
    }
  })
}

module.exports = fn